package clara.azin.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;

import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML.Attribute;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.html.HTMLEditorKit.ParserCallback;
import javax.swing.text.html.parser.ParserDelegator;

public class LinksParser extends ParserCallback{

	
	LinkedList<URL> temporary;
	String host;
	Node node;
	public LinksParser(String host,Node node) {
		super();
		this.temporary = new LinkedList<URL>();
		this.host = host;
		this.node = node;
	}

	public LinkedList<URL> retrieveURL() throws IOException {
		
		StringReader stringReader = null;
		temporary = new LinkedList<URL>();
		try{
			stringReader = new StringReader( getHTML(node.url) ) ;
			//creiamo un'istanza del parser Html
			ParserDelegator p = new ParserDelegator();
			p.parse(stringReader, this, true);
		}catch(IOException e){
			e.printStackTrace();
			return temporary;
		}
		
		return temporary;
		
		
		
	}
	
	private String getHTML(URL url) throws IOException {
		
		HttpURLConnection connection;
		String temp;
		BufferedReader htmlReader;
		InputStreamReader inputStream;
		StringBuffer buffer ;
		buffer = new StringBuffer();
		connection = (HttpURLConnection) url.openConnection();
		connection.setReadTimeout(2000);
		inputStream = new InputStreamReader(connection.getInputStream(), "ISO-8859-1" );
		htmlReader = new BufferedReader(inputStream);
		temp = htmlReader.readLine();
		buffer.append(temp);
	
		while(temp!=null){
			temp = htmlReader.readLine();
			if(temp!=null) 
				buffer.append(temp);
		}
		return buffer.toString();
	}
	
	@Override
	public void handleStartTag(Tag t, MutableAttributeSet a, int pos) {		
		String url_value = (String) a.getAttribute(Attribute.HREF);
		URL url;
		if(t == Tag.A && url_value != null)	{
			try {
				//System.out.println("Esamino url "+ url_value);
				// Internal links does not interest us
				if(url_value.startsWith("#") || url_value.startsWith("mailto")) 
					return;
				else if(!url_value.contains("http"))
					url = new URL("http", host, url_value);
				else
					url = new URL((String) a.getAttribute(Attribute.HREF));
				
				// non vengono aggiunte copie
				if(temporary.contains(url) == false)
					temporary.add( url );
				
			} catch (MalformedURLException e) {
				//e.printStackTrace();
				System.err.println(e.getMessage());
				return;
			}
		}
	}
	
	
}
